<template>
  <div>
    <el-dialog :title="'库存调整'" :visible.sync="addEditIsDialog_c" @close="resetForm('formName')" width="70%">
      <el-form :model="ruleForm" :rules="rules" ref="formName" label-width="120px" class="demo-ruleForm" :class="{ 'form-rules-show': seeType }">
        <el-row>
          <el-col :span="24">
            <el-table :data="tableData" :border="true" :header-cell-style="tabHeadStyle" :cell-style="tabcellStyle" :row-style="rowStyle" height="500" :span-method="objectSpanMethod">
              <el-table-column label="织物类型" align="center">
                <template>
                  <el-table-column prop="classify_text" label="织物名称" align="center" min-width="90"> </el-table-column>
                  <el-table-column prop="size_text" label="尺码" align="center" min-width="90"> </el-table-column>
                </template>
              </el-table-column>
              <el-table-column prop="counts" label="调整前库存" align="center"> </el-table-column>
              <el-table-column label="调整后库存" align="center">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.ajCounts" type="number" min="0" max="9999999" @input="calculateTotal(scope.row)"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="count" label="库存差值" align="center">
                <template slot-scope="scope">
                  {{ scope.row.count }}
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('formName')">关 闭</el-button>
        <el-button type="primary" @click="submitForm('formName')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
import { doctorClothAreaInventoryInfo, adjustInventory } from "@/api/stock";

export default {
  props: {
    addEditId: {
      type: String,
      default: "",
    },
    startdate: {
      type: String,
      default: "",
    },
    areaName: {
      type: String,
      default: "",
    },
    enddate: {
      type: String,
      default: "",
    },
    addEditStatus: {
      type: String,
      default: "add",
    },
    addEditIsDialog: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 表头样式
      tabHeadStyle: {
        "background-color": "#f5f7fa",
        color: "#303133",
        "font-weight": "bold",
        "text-align": "center",
      },
      // 行样式
      tabcellStyle: {
        color: "#666",
      },
      rowStyle: {
        height: "20px",
      },
      ruleForm: {
        // 表单字段
        name: "",
      },
      rules: {
        // 表单规则
        name: [{ required: true, message: "请输入院区名称", trigger: "blur" }],
      },
      addEditIsDialog_c: false, // 弹窗是否显示
      seeType: false, // 是否禁用
      tableData: [],
      tableFields: [],
      date: [],
      spanArr: [],
      ajCounts: 0,
      variance: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  watch: {
    addEditIsDialog(val) {
      this.addEditIsDialog_c = val;
      if (this.addEditIsDialog_c) {
        // 添加
        if (this.addEditStatus == "add") {
          this.ruleForm.id = "";
          this.seeType = false;
        }

        // 编辑
        if (this.addEditStatus == "edit") {
          this.ruleForm.id = this.addEditId;
          this.seeType = false;
          this.getDetail();
        }

        // 查看
        if (this.addEditStatus == "see") {
          this.ruleForm.id = this.addEditId;
          this.seeType = true;
          this.getDetail();
        }
      }
    },
  },
  methods: {
    // 详情
    getDetail() {
      doctorClothAreaInventoryInfo({ area_id: this.addEditId }).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data;

          this.getSpanArr();
        }
      });
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.tableData = this.tableData.filter(item => item.hasOwnProperty('count'));
          adjustInventory({area_id:this.addEditId,items:JSON.stringify(this.tableData)}).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });

              // 关闭弹窗
              this.$parent.closeAddEdit();
              // 刷新列表
              this.$parent.onSubmit();
            }
          });
        }
      });
    },
    // 计算 name 列的合并规则
    getSpanArr() {
          this.spanArr = [];
          let pos = 0; // 记录当前合并组的起始索引
          for (let i = 0; i < this.tableData.length; i++) {
            if (i === 0) {
              // 第一行，肯定是新组的开始
              this.spanArr.push(1);
              pos = 0;
            } else {
              // 判断当前行的 name 是否与上一行相同
              if (this.tableData[i].classify_text === this.tableData[i - 1].classify_text) {
                // 相同，则起始索引处的合并行数+1，当前行标记为0（被合并）
                this.spanArr[pos] += 1;
                this.spanArr.push(0);
              } else {
                // 不同，则当前行是新组的开始，标记为1，并更新起始索引
                this.spanArr.push(1);
                pos = i;
              }
            }
          }
        },
        // 表格合并方法
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
          // 只处理第一列（name列）
          if (columnIndex === 0) {
            const rowspan = this.spanArr[rowIndex];
            const colspan = rowspan > 0 ? 1 : 0;
            // 关键：被合并的单元格返回 [0, 0]
            return {
              rowspan: rowspan,
              colspan: colspan
            };
          }
        },
    // 计算
    calculateTotal(row) {
     row.count = row.ajCounts - row.counts;
    },
    // 日期切换
    handleDate() {
      if (this.date && this.date.length == 2) {
        this.ruleForm.startdate = this.date[0];
        this.ruleForm.enddate = this.date[1];
      } else {
        this.ruleForm.startdate = "";
        this.ruleForm.enddate = "";
      }

      this.getDetail();
    },
    // 取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$parent.closeAddEdit();
    },
  },
};
</script>

<style lang="less" scoped>
.demo-ruleForm {
  width: 95%;
  margin: 0 auto;
  padding-top: 10px;
}
</style>
